package com.xinqi.modules.sys.dict.service.impl;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xinqi.common.base.error.CommonErrors;
import com.xinqi.common.base.response.PageInfo;
import com.xinqi.common.base.response.Param;
import com.xinqi.common.mybatis.utils.Pages;
import com.xinqi.common.mybatis.utils.Queries;
import com.xinqi.modules.sys.dict.convert.DictDocumentConvert;
import com.xinqi.modules.sys.dict.domain.DictDocumentEntity;
import com.xinqi.modules.sys.dict.dto.req.DictDocumentCreateDTO;
import com.xinqi.modules.sys.dict.dto.req.DictDocumentDeleteDTO;
import com.xinqi.modules.sys.dict.dto.req.DictDocumentQueryDTO;
import com.xinqi.modules.sys.dict.dto.req.DictDocumentUpdateDTO;
import com.xinqi.modules.sys.dict.dto.rsp.DictDocumentResultDTO;
import com.xinqi.modules.sys.dict.dto.rsp.DictDocumentTreeResultDTO;
import com.xinqi.modules.sys.dict.manager.DictDocumentManager;
import com.xinqi.modules.sys.dict.service.DictDocumentService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import javax.validation.Valid;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 文档分类字典表服务层实现
 *
 * @author: gzy
 * @date: 2023/05/28
 */
@Validated
@Service("dictDocumentService")
@RequiredArgsConstructor
public class DictDocumentServiceImpl implements DictDocumentService {
    private final DictDocumentConvert dictDocumentConvert;
    private final DictDocumentManager dictDocumentManager;

    /**
     * 分页查询 文档分类字典表数据
     */
    @Override
    @DS("slaver")
    public PageInfo<DictDocumentResultDTO> page(Param pageable, DictDocumentQueryDTO query) {
        Page<DictDocumentResultDTO> page = dictDocumentManager.findByPage(Pages.page(pageable), query);
        return Pages.convert(page);
    }

    /**
     * 查询 文档分类字典表数据
     */
    @Override
    public List<DictDocumentResultDTO> find(DictDocumentQueryDTO query) {
        return dictDocumentManager.list(wrapper(query)).stream()
            .map(dictDocumentConvert::convert).collect(Collectors.toList());
    }

    private LambdaQueryWrapper<DictDocumentEntity> wrapper(DictDocumentQueryDTO query) {
        LambdaQueryWrapper<DictDocumentEntity> wrapper = Queries.lambda();
        Queries.accept(query.getId(), v -> wrapper.eq(DictDocumentEntity::getId, v));
        return wrapper;
    }

    /**
     * 根据id查询 文档分类字典表数据
     */
    @Override
    public DictDocumentResultDTO findById(Long id) {
        CommonErrors.BAD_REQUEST.check(Objects.nonNull(id), "ID不能为空");
        return Optional.ofNullable(dictDocumentManager.findById(id)).map(dictDocumentConvert::convert).orElse(null);
    }

    /**
     * 新增 文档分类字典表数据
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long insert(@Valid DictDocumentCreateDTO dto) {
        DictDocumentEntity entity = dictDocumentConvert.create(dto);
        CommonErrors.BAD_REQUEST.check(this.selectCountByCode(entity.getDictCode()) == 0, "字典编码不能重复");
        if (Objects.nonNull(entity.getParentId()) && !entity.getParentId().equals(0L)) {
            DictDocumentEntity parent = this.dictDocumentManager.getById(entity.getParentId());
            entity.setParentDictCode(parent.getDictCode());
            entity.setParentDictName(parent.getDictName());
        } else {
            entity.setParentId(0L);
            entity.setParentDictName("无");
        }
        if (Objects.isNull(entity.getSort())) {
            entity.setSort(this.generateSort(entity.getParentId()));
        }
        dictDocumentManager.save(entity);
        return entity.getId();
    }

    private Long generateSort(long parentId) {
        return dictDocumentManager.generateSort(parentId);
    }

    /**
     * 通过dictCode查询数量
     *
     * @param dictCode
     * @return
     */
    private int selectCountByCode(String dictCode) {
        return dictDocumentManager.selectCountByCode(dictCode);
    }

    /**
     * 根据id修改 文档分类字典表数据
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateById(@Valid DictDocumentUpdateDTO dto) {
        Optional.ofNullable(dictDocumentManager.getById(dto.getId()))
            .orElseThrow(() -> CommonErrors.BAD_REQUEST.asException("数据不存在"));
        DictDocumentEntity entity = dictDocumentConvert.update(dto);
        if (Objects.nonNull(entity.getParentId()) && !entity.getParentId().equals(0L)) {
            DictDocumentEntity parent = this.dictDocumentManager.getById(entity.getParentId());
            entity.setParentDictCode(parent.getDictCode());
            entity.setParentDictName(parent.getDictName());
        } else {
            entity.setParentId(0L);
            entity.setParentDictName("无");
        }
        return dictDocumentManager.updateById(entity);
    }

    /**
     * 根据id删除 文档分类字典表数据
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteById(Long id) {
        CommonErrors.BAD_REQUEST.check(Objects.nonNull(id), "ID不能为空");
        return dictDocumentManager.removeOutById(id);
    }

    /**
     * 根据id删除 文档分类字典表数据
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteById(DictDocumentDeleteDTO dto) {
        return deleteById(dto.getId());
    }

    @Override
    public List<DictDocumentResultDTO> findAll() {
        return dictDocumentManager.findAll();
    }

    @Override
    public List<DictDocumentTreeResultDTO> findAllTree() {
        return dictDocumentManager.findAllTree();
    }

    @Override
    public List<DictDocumentResultDTO> findSubListByParentId(Long parentId) {
        return dictDocumentManager.findSubListByParentId(parentId);
    }

    @Override
    public List<DictDocumentResultDTO> findSubListByParentCode(String parentCode) {
        return dictDocumentManager.findSubListByParentCode(parentCode);
    }

}
